<?php
/*
Cogumelo v0.1 - Map-Experience
Copyright (C) 2008 Innoto Gestión para el Desarrollo Social S.L. <mapinfo@map-experience.com>

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
USA.
*/

require_once("Classes/Model/DAO/UseradminDAO.inc");
require_once("Classes/Model/VO/UseradminVO.inc");
require_once("Classes/DBMS/Mysql/MysqlDAO/MysqlDAOutils.inc");

//
//	Mysql useradmin DAO
//
class MysqlUseradminDAO extends UseradminDAO
{
    
	//
	// Constructor (calls parents for getting log and error controllers)
	//
	function __construct()
	{
	 parent::__construct();   
	}
	
	//
	// Creates an VO from a query result;
	//
	// Returns: useradminVO
	private function VOGenerator($res)
	{
		$row = mysqli_fetch_assoc($res);
		return new UseradminVO(
				  $row[useradmin_id],
				  $row[useradmin_login],
				  $row[useradmin_passwd],
				  $row[useradmin_name],		
				  $row[useradmin_time_lastlogin],
				  $row[useradmin_level],
				  $row[useradmin_time_lastchangepasswd],
				  $row[useradmin_oldpassword1],
				  $row[useradmin_oldpassword2],
				  $row[useradmin_oldpassword3]
		);
	}
	
	//
	// Creates an VO array from a query result;
	//
	// Returns: Array useradminVOs
	private function VOArrayGenerator($res)
	{
		while($row = mysqli_fetch_assoc($res))		
			$list[] = new UseradminVO(
				  $row[useradmin_id],
				  $row[useradmin_login],
				  $row[useradmin_passwd],	
				  $row[useradmin_name],					  
				  $row[useradmin_time_lastlogin],
				  $row[useradmin_level],
				  $row[useradmin_time_lastchangepasswd],
				  $row[useradmin_oldpassword1],
				  $row[useradmin_oldpassword2],
				  $row[useradmin_oldpassword3]
			);
			
		return $list;
	}
	
	
	
	//
	//	Create New User from useradminVO. Return user created ID.
	//
	function Create($connection, $useradmin)
	{
		// SQL Query
		$StrSQL = sprintf("INSERT INTO `useradmin` (
		    useradmin_login ,
		    useradmin_name ,
		    useradmin_passwd ,		   
		    useradmin_time_lastlogin,
		    useradmin_time_lastchangepasswd		    
		    )
		  VALUES(	
		  			'%s', '%s', SHA1('%s'), '%s', '%s'
				)
		  		;",
			$useradmin->getLogin(),
			$useradmin->getName(),			
			$useradmin->getPasswd(),			
			$useradmin->getTimeLastLogin(),
			$useradmin->getTimelastchangepasswd()
		);
		
		if(!$res = execSQL($connection,$StrSQL))
		{
			$this->errorcontrol->raiseError(1001,"mysqluseradminDAO:Create(): ".$connection->error." QUERY: ".$StrSQL);
			return false;
		}
		else { $this->logcontrol->addLogLine("SQL Query: mysqluseradminDAO:Create(): ".$StrSQL, 5); return $connection->insert_id; }		
	}
	
	
	//
	//	Definitive user removal
	//
	function Destroy($connection, $useradminID)
	{
		// SQL Query
		$StrSQL = "DELETE FROM `useradmin` WHERE `useradmin_id` = ".$useradminID;
		
		if(!$res = execSQL($connection,$StrSQL))
		{
			$this->errorcontrol->raiseError(1001,"mysqluseradminDAO:Destroy(): ".$connection->error." QUERY: ".$StrSQL);
			return false;
		}
		else { $this->logcontrol->addLogLine("SQL Query: mysqluseradminDAO:Destroy(): ".$StrSQL, 5); return true; }	
	}
	
	//
	//	Find an User by ID
	//
	//	Return: useradminVO (null if 0 rows)
	function Find($connection, $useradminID)
	{
		// SQL Query
		$StrSQL = "SELECT * FROM `useradmin` WHERE `useradmin_id` = ".$useradminID;
		
		
		if(!$res = execSQL($connection,$StrSQL))
		{
		   $this->errorcontrol->raiseError(1001,"mysqluseradminDAO:Find(): ".$connection->error." QUERY: ".$StrSQL);
		   return false;
		}		
		else
		{
		    $this->logcontrol->addLogLine("SQL Query: mysqluseradminDAO:Find(): (".$res->num_rows." rows found) ".$StrSQL, 5);
			if($res->num_rows != 0)
			    return $this->VOGenerator($res);
			else
				return false;
		}		
	}

	
	//
	//	Find an User by login
	//
	//	Return: useradminVO	(null if 0 rows)
	function FindByLogin($connection, $login)
	{
		
		// SQL Query
		$StrSQL = "SELECT * FROM `useradmin` WHERE `useradmin_login` = '".$login."'";
		if(!$res = execSQL($connection,$StrSQL))
		{
		   $this->errorcontrol->raiseError(1001,"mysqluseradminDAO:FindByLogin(): ".$connection->error." QUERY: ".$StrSQL);
		   return false;
		}		
		else
		{
		    $this->logcontrol->addLogLine("SQL Query: mysqluseradminDAO:FindByLogin(): (".$res->num_rows." rows found) ".$StrSQL, 5);
			if($res->num_rows != 0)
			    return $this->VOGenerator($res);
			else
				return false;
		}		
	}

	
	
	//
	//	Authenticate administrator user
	//
	//	Return: useradminVO	(null if 0 rows)
	function AuthenticateUseradmin($connection, $login, $pass)
	{		
		// SQL Query
		$StrSQL = "SELECT * FROM `useradmin` WHERE `useradmin_login` = '".$login."' and `useradmin_passwd` = SHA1('".$pass."');";
		$StrSQLSecure = "SELECT * FROM `useradmin` WHERE `useradmin_login` = '".$login."' and `useradmin_passwd` = SHA1('XXX');"; // Secure SQL Query for log dump
		if(!$res = execSQL($connection,$StrSQL))
		{
		   $this->errorcontrol->raiseError(1001,"mysqluseradminDAO:AuthenticateUseradmin(): ".$connection->error." QUERY: ".$StrSQLSecure);
		   return false;
		}		
		else
		{
		    $this->logcontrol->addLogLine("SQL Query: mysqluseradminDAO:AuthenticateUseradmin(): ".$StrSQLSecure, 5);
			if($res->num_rows == 1)
				return $this->VOGenerator($res);
			else
				return false;
		}		

	}
	
	
	//
	// Generate WHERE clause for SQL query on ListAll functions
	//
	function GenerateFilter($FILTER)
	{
		if(!$FILTER) 
			$whereSTR = '';
		else {
			$whereSTR = ' WHERE 1 ';
			if($FILTER['find']) $whereSTR .= "AND useradmin_name LIKE '%".$FILTER['find']."%' OR useradmin_login LIKE '%".$FILTER['find']."%'";
		}
		
		return($whereSTR);			 
	}
	
	//
	//	Generic list
	//
	//	Return: array of useradminVOs
	function ListAll($connection, $FILTER, $RANGE, $ORDER)
	{

		$whereSTR = $this->GenerateFilter($FILTER);
		
		// ORDER IT !
		$orderSTR = OrderByString($ORDER);

		//// If is RANGE
		if($RANGE)
			$rangeSTR = sprintf(" LIMIT %s, %s ", $RANGE[0], $RANGE[1]);


		// SQL Query
		$StrSQL = "SELECT * FROM `useradmin` ".$whereSTR.$orderSTR.$rangeSTR;
		
		if(!$res = execSQL($connection,$StrSQL))
		{
		   $this->errorcontrol->raiseError(1001,"mysqluseradminDAO:ListAll(): ".$connection->error." QUERY: ".$StrSQL);
		   return false;
		}		
		else
		{
		    $this->logcontrol->addLogLine("SQL Query: mysqluseradminDAO:ListAll(): (".$res->num_rows." rows found) ".$StrSQL, 5);
			if($res->num_rows != 0)
				return $this->VOArrayGenerator($res);
			else
				return false;
		}		
	}
 	//
	//	rows number
	function ListAllCount($connection, $FILTER)
	{			
		$whereSTR = $this->GenerateFilter($FILTER);
		
		// SQL Query
		$StrSQL = "SELECT COUNT(*) FROM `useradmin`".$whereSTR.";";
		
		if(!$res = execSQL($connection,$StrSQL))
		{
		   $this->errorcontrol->raiseError(1001,"mysqluseradminDAO:ListAllCount(): ".$connection->error." QUERY: ".$StrSQL);
		   return false;
		}		
		else 
		{
			while($rowsNO = mysqli_fetch_assoc($res))
			{ $this->logcontrol->addLogLine("SQL Query: mysqluseradminDAO:ListAllCount(): (".$rowsNO['COUNT(*)']." rows found) ".$StrSQL, 5); return $rowsNO['COUNT(*)']; }
		}
	}
	
	
	//
	//	Use an useradminVO to update a Useradmin data (No passwd update). 
	//	
	function Update($connection, $useradmin)
	{
		// SQL Query
		
		$StrSQL = sprintf("UPDATE `useradmin` SET 		   	    		    
		    useradmin_login = '%s',		    		    
		    useradmin_name = '%s',
		    useradmin_level = %s
		  WHERE `useradmin_id` = %s ;",													
			$useradmin->getLogin(),
			$useradmin->getName(),
			$useradmin->getLevel(),
			$useradmin->getId()
		);
		
		if(!$res = execSQL($connection,$StrSQL))
		{
			$this->errorcontrol->raiseError(1001,"mysqluseradminDAO:Update(): ".$connection->error." QUERY: ".$StrSQL);
			return false;
		}
		else { $this->logcontrol->addLogLine("SQL Query: mysqluseradminDAO:Update(): ".$StrSQL, 5); return true; }	
	}
	
	//
	//	Use an useradminVO to update a Useradmin password. 
	//	
	function UpdatePasswd($connection, $newupdateadmin)
	{

		// SQL Query
		$StrSQL = sprintf("UPDATE `useradmin` SET 		   	    
		    useradmin_passwd = SHA1('%s'),
		    useradmin_oldpassword1 = '%s',
		    useradmin_oldpassword2 = '%s',
		    useradmin_oldpassword3 = '%s',
		    useradmin_time_lastchangepasswd = '%s'		    		    
		  WHERE `useradmin_id` = %s ;",						
			$newupdateadmin->getPasswd(),
			$newupdateadmin->getOldpassword1(),
			$newupdateadmin->getOldpassword2(),
			$newupdateadmin->getOldpassword3(),
			$newupdateadmin->getTimelastchangepasswd(),						
			$newupdateadmin->getId()
		);
		
		//print($StrSQL);
		$StrSQLSecure = sprintf("UPDATE `useradmin` SET 		   	    
		    useradmin_passwd = SHA1('XXX'),
		    useradmin_oldpassword1 = 'XXX',
		    useradmin_oldpassword2 = 'XXX',
		    useradmin_oldpassword3 = 'XXX',		
		    useradmin_time_lastchangepasswd = '%s'	    		    
		  WHERE `useradmin_id` = %s ;",		
			$newupdateadmin->getTimelastchangepasswd(),											
			$newupdateadmin->getId()
		);
		
		if(!$res = execSQL($connection,$StrSQL))
		{
			$this->errorcontrol->raiseError(1001,"mysqluseradminDAO:Updatepass(): ".$connection->error." QUERY: ".$StrSQLSecure);
			return false;
		}
		else { $this->logcontrol->addLogLine("SQL Query: mysqluseradminDAO:UpdatePassword(): ".$StrSQLSecure, 5); return true; }

	}

	
	//
	//	Use an useradminVO to update a Useradmin password. 
	//	
	function UpdateTime($connection, $useradmin)
	{
		// SQL Query
		$StrSQL = sprintf("UPDATE `useradmin` SET 		   	    
		    useradmin_time_lastlogin = '%s'		    		    
		  WHERE `useradmin_id` = %s ;",						
			$useradmin->getTimeLastLogin(),						
			$useradmin->getId()
		);
		
		if(!$res = execSQL($connection,$StrSQL))
		{
			$this->errorcontrol->raiseError(1001,"mysqluseradminDAO:UpdateTime(): ".$connection->error." QUERY: ".$StrSQL);
			return false;
		}
		else { $this->logcontrol->addLogLine("SQL Query: mysqluseradminDAO:UpdateTime(): ".$StrSQL, 5); return true; }
	}
	
	
}

?>